<script setup>
  import { ref, onMounted } from 'vue'
  import { queryStuApi, addStuApi, dealViolationApi, queryStuByIdApi, updateStuApi, deleteStuByIdApi } from '@/api/student'
  import { queryClazzListApi} from '@/api/clazz'
  import { ElMessage, ElMessageBox } from 'element-plus';

  const degrees = ref([{ name: '初中', value: '1' },{ name: '高中', value: '2' },{ name: '大专', value: '3' },{ name: '本科', value: '4' },{ name: '硕士', value: '5' },{ name: '博士', value: '6' }])
  const genders = ref([{ name: '男', value: 1 },{ name: '女', value: 2 }])
  const isCollege = ref([{ name: '是', value: 1 },{ name: '否', value: 0 }])

  const clazzs = ref([])

  const stuList = ref([])

  const stuRef = ref()

  const student = ref({
    name:'',
    no:'',
    gender:'',
    phone:'',
    idCard:'',
    isCollege:'',
    address:'',
    degree:'',
    graduationDate:'',
    clazzId:''
  })

  const searchStu = ref({
    name: '',
    degree: '',
    clazzId:''
  })

  const search = async () => {
    const res = await queryStuApi(searchStu.value.name,
                                  searchStu.value.degree,
                                  searchStu.value.clazzId,
                                  currentPage.value,
                                  pageSize.value)
    if (res.code){
      stuList.value = res.data.rows
      total.value = res.data.total
    }
  }

  const clear = () => {
    searchStu.value = {
      name: '',
      degree: '',
      clazzId: '',
    }
    search()
  }

  const searchClazz = async () => {
    const res = await queryClazzListApi()
    if (res.code){
      clazzs.value = res.data
    }
  }

  onMounted(() => {
    search()
    searchClazz()
  })

  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const handleSizeChange = (val) => {
    search()
  }
  const handleCurrentChange = (val) => {
    search()
  }

  const dialogVisible = ref(false)
  const dialogTitle = ref('')

  const add = () => {
    student.value = {
      name:'',
      no:'',
      gender:'',
      phone:'',
      idCard:'',
      isCollege:'',
      address:'',
      degree:'',
      graduationDate:'',
      clazzId:''
    }
    dialogVisible.value = true
    dialogTitle.value = '新增员工'
    if (stuFormRef.value){
      stuFormRef.value.resetFields()
    }
  }

  const edit = async (id) => {
    if (stuFormRef.value){
      stuFormRef.value.resetFields()
    }
    dialogVisible.value = true
    dialogTitle.value = '修改学员'
    const res = await queryStuByIdApi(id)
    student.value = res.data
  }

  const save = async () => {
    await stuFormRef.value.validate (async(valid,fields)=>{
      if (valid){
        let res
        if (student.value.id){
          res = await updateStuApi(student.value)
        }else{
          res = await addStuApi(student.value)
        }
        if (res.code){
          ElMessage.success('保存成功')
          dialogVisible.value = false
          search()
        }else{
          ElMessage.error('保存失败')
        }
      }else{
        ElMessage.error('校验失败')
      }
    })
  }

  const selectIds = ref([])
  const handleSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.id)
  }
  const delByIds = () => {
    ElMessageBox.confirm(
    '确定要删除此数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
    ).then(async () => {
      const res = await deleteStuByIdApi(selectIds.value)
      if (res.code){
        ElMessage.success('删除成功')
        search()
      }else{
        ElMessage.error(res.msg)
      }
    }).catch(() => {
      ElMessage.info('取消操作')
    })
  }

  const del = (id) => {
    ElMessageBox.confirm(
    '确定要删除此数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
    ).then(async () => {
      const res = await deleteStuByIdApi(id)
      if (res.code){
        ElMessage.success('删除成功')
        search()
      }else{
        ElMessage.error(res.msg)
      }
    }).catch(() => {
      ElMessage.info('取消操作')
    })
  }

  const rules = ref({
    name: [
      { required: true, message: '请输入学员名', trigger: 'blur' },
      { min: 2, max: 10, message: '学员长度应在2到10个字符之间', trigger: 'blur' }
    ],
    no: [
      { required: true, message: '请输入学号', trigger: 'blur' },
      { min: 10, max: 10, message: '学号长度必须为10位', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'change' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ],
    idCard: [
      { required: true, message: '请输入身份证号', trigger: 'blur' },
      { pattern: /^(^\d{15}$|^\d{17}([0-9]|X)$)/, message: '请输入有效的身份证号', trigger: 'blur' }
    ],
    isCollege: [
      { required: true, message: '请选择', trigger: 'change' }
    ],
    address: [
      { min: 0, max: 100, message: '长度限制为10位', trigger: 'blur' }
    ]
  })

  const stuFormRef = ref()

  const formTitle = ref('提示')
  const showDialog = ref(false)
  const vio_stu = ref()
  const score = ref()

  const dealViolation = (id) => {
    score.value = null
    showDialog.value = true
    vio_stu.value = id
  }

  const confirm = async () => {
    if (vio_stu.value && vio_stu.value != 0){
      if (score.value && score.value > 0){
        const res = await dealViolationApi(vio_stu.value,score.value)
        if (res.code){
          ElMessage.success('处理成功')
          showDialog.value = false
          search()
        }else{
          ElMessage.error('处理失败')
        }
      }else{
        ElMessage.error('请输入扣分')
      }
    }else{
      ElMessage.error('请选择学员')
    }
  }

</script>

<template>
  <h1>学员管理</h1>
  <!-- 表单 -->
  <el-form :inline="true" :model="searchStu" class="stu-search" >
    <el-form-item label="姓名">
      <el-input v-model="searchStu.name" placeholder="请输入学生姓名" clearable />
    </el-form-item>
    <el-form-item label="学历">
      <el-select v-model="searchStu.degree" placeholder="请选择" clearable >
        <el-option v-for="d in degrees" :label="d.name" :value="d.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级">
      <el-select v-model="searchStu.clazzId" placeholder="请选择" clearable >
        <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 增删操作按钮 -->
  <div class="button-group">
    <el-button type="primary" @click="add">+ 新增学员</el-button>
    <el-button type="danger" @click="delByIds">- 批量删除</el-button>
  </div>
  <!-- 表格 -->
  <el-table :data="stuList" @selection-change="handleSelectionChange" border style="width: 100%;">
    <el-table-column type="selection" width="50" align="center"/>
    <el-table-column prop="name"  label="姓名" width="80" align="center"/>
    <el-table-column prop="no" label="学号" width="120" align="center"/>
    <el-table-column prop="clazzName" label="班级" width="150" align="center"/>
    <el-table-column prop="gender" label="性别" width="70" align="center">
      <template #default="scope">
        {{ scope.row.id == 1 ? '男' : '女'}}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="120" align="center"/>
    <el-table-column prop="degree" label="最高学历" width="90" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree==1">初中</span>
        <span v-else-if="scope.row.degree==2">高中</span>
        <span v-else-if="scope.row.degree==3">大专</span>
        <span v-else-if="scope.row.degree==4">本科</span>
        <span v-else-if="scope.row.degree==5">硕士</span>
        <span v-else-if="scope.row.degree==6">博士</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="90" align="center"/>
    <el-table-column prop="violationScore" label="违纪扣分" width="90" align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="190" align="center"/>
    <el-table-column fixed="right" label="操作" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="edit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="warning" @click="dealViolation(scope.row.id)">违纪</el-button>
        <el-button size="small" type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 增改学员 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    {{ student }}
    <el-form :model="student" :rules="rules" ref="stuFormRef" label-width="150px">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="student.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="student.no" placeholder="请输入学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="student.gender" placeholder="请选择" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="student.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option v-for="i in isCollege" :label="i.name" :value="i.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
              <el-option v-for="d in degrees" :label="d.name" :value="d.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker v-model="student.graduationDate" type="date" style="width: 100%;" placeholder="请选择毕业时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">
            <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
    </el-form>
    
    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 违纪扣分窗口 -->
  <el-dialog v-model="showDialog" :title="formTitle" width="30%">
    <p>请输入违纪扣分</p><br>
    <el-form>
      <el-input v-model="score" autocomplete="off"></el-input>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 分页条 -->
  <div class="pagination-block">
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  </div>
</template>

<style scoped>
  .stu-search {
    margin: 20px 0;
  }
  .button-group {
    margin-bottom: 10px;
  }
  .pagination-block {
    margin: 20px 0;
  }
  .avatar {
    height: 40px;
  }
  .avatar-uploader .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    text-align: center;
    border-radius: 10px;
    /* 添加灰色的虚线边框 */
    border: 1px dashed var(--el-border-color);
  }
</style>